package com.hxit.huaxiamelongarden.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hxit.huaxiamelongarden.domin.dto.ContentDto;
import com.hxit.huaxiamelongarden.domin.dto.IndexDto;
import com.hxit.huaxiamelongarden.domin.po.Content;
import com.hxit.huaxiamelongarden.domin.po.Tags;
import com.hxit.huaxiamelongarden.mapper.ContentMapper;
import com.hxit.huaxiamelongarden.service.ContentService;
import com.hxit.huaxiamelongarden.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ContentImpl
 * @Author 12694
 * @Date 2025/1/23 16:59
 * @Version 1.0
 **/
@Service
public class ContentServiceImpl implements ContentService {
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private TagService tagService;
    /*根据用户id查询帖子内容*/
    @Override
    public List<Content> getCommentsByUserId(int userId) {
        return contentMapper.getCommentsByUserId(userId);
    }

    //首页默认查询所有内容
    @Override
    public List<Content> getAllContent() {
        List<Content> contents = contentMapper.selectList(null);
        return contents;
    }

    //根据内容或话题模糊搜索
    @Override
    public List<Content> getSearchContent(IndexDto indexDto) {
        LambdaQueryWrapper<Content> queryWrapper=new LambdaQueryWrapper<>();
        if (indexDto.getContent()!=null){
            queryWrapper.like(Content::getContent,indexDto.getContent());
        }
        if (indexDto.getTitle()!=null){
            queryWrapper.like(Content::getTitle,indexDto.getTitle()).orderByDesc(Content::getCreatedAt);
        }
        List<Content> contents = contentMapper.selectList(queryWrapper);
        return contents;
    }

    //根据标签查找
    @Override
    public List<Content> findTagByTagName(IndexDto indexDto) {
        List<Integer> collect = indexDto.getTags().stream().map(tag -> {
            Tags tagPo = tagService.findTagByTagName(tag.getTagName());
            return tagPo.getTagId();
        }).collect(Collectors.toList());
        List<Content> contentList = contentMapper.findTagByIds(collect);
        return contentList;
    }

    //新增帖子
    @Override
    public void addContent(ContentDto contentDto) {
        Content content = BeanUtil.copyProperties(contentDto, Content.class);
        contentMapper.insert(content);
    }

    //根据id查找帖子
    @Override
    public Content findContentById(int contentId) {
        LambdaQueryWrapper<Content> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Content::getContentId,contentId);
        Content content = contentMapper.selectOne(queryWrapper);
        return content;
    }
}
